package com.test.javalang;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

public class CallPython {

    /**
     * print_all_param.py
     import sys

     if __name__ == "__main__":
     print("参数总数:", len(sys.argv))
     for i, arg in enumerate(sys.argv):
     print(f"参数 {i}: {arg}")
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        runPythonScript("D:\\tmp\\print_all_param.py", "");
        
    }

    /**
     * 执行python脚本
     *
     * @param scriptPath 脚本路径
     * @param serialNo   合同流水号
     * @throws IOException 路径下脚本不存在
     */
    private static void runPythonScript(final String scriptPath, final String serialNo)
            throws IOException {
        final ProcessBuilder pb = new ProcessBuilder();
        pb.command("python", scriptPath, "param1", serialNo);
        final Process start = pb.start();
        pb.redirectErrorStream(true); // 合并标准输出和错误输出
        try (final InputStream is = start.getInputStream();
             final InputStreamReader isr = new InputStreamReader(is);
             final BufferedReader reader = new BufferedReader(isr)) {
            // 读取 Python 脚本输出
            reader.lines().forEach(System.out::println);

            // 存在python进程长时间未返回的情况，设置超时时间以便告警
            final boolean result = start.waitFor(1, TimeUnit.MINUTES);


        } catch (final Exception e) {
            // 不确定会抛出哪些异常，这里捕获exception，返回false,调用处根据返回值告警
        } finally {
            start.destroy();
        }

    }
}



